import { type FC, useMemo } from 'react';
import { useMemoizedFn } from 'ahooks';
import styles from './styles.module.less';
import Chats from './components/Chats';
import Socket from '../Socket';
import { Storage } from '@/libs/storage';
import logo from '@/assets/logo.svg'
import type { AiChatRobotProps } from './types';
import { ChatHistoryType } from './components/ChatHistory/types';

const store = new Storage('@@chats');

const AiChatRobot: FC<AiChatRobotProps> = (props) => {

  const onSaveChat = useMemoizedFn((history: ChatHistoryType) => {
    const histories = store.getItem<ChatHistoryType[]>('s') || [];
    const index = histories.findIndex(e => e.id === history.id);
    if (index > -1) {
      histories[index] = history;
    } else {
      histories.push(history);
    }
    store.setItem('s', histories);
  });

  const histories = useMemo(() => {
    return store.getItem<ChatHistoryType[]>('s') || [];
  }, []);

  return (
    <div className={styles.chat_wrapper}>
      <div className={styles.chat_content}>
        <div className={styles.chat_header}>
          <img src={logo} style={{ height: 36 }} />
        </div>
        <div className={styles.chat_view}>
          <Socket token={props.token}>
            <Chats
              onSaveChat={onSaveChat}
              defaultHistories={histories}
            />
          </Socket>
        </div>
      </div>
    </div>
  );
}

export default AiChatRobot;